package com.bestv.search.common.dao.hibernate;

import com.bestv.search.common.dao.InfoHeaderItemDao;
import com.bestv.search.common.model.InfoHeaderItem;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;

import java.util.ArrayList;
import java.util.List;

public class InfoHeaderItemDaoHibernate extends GenericDaoHibernate<InfoHeaderItem, Long> implements InfoHeaderItemDao {

    public InfoHeaderItemDaoHibernate() {
        super(InfoHeaderItem.class);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<InfoHeaderItem> getInfoHeaderItemByHeaderId(long headerId) {
        String hql = "from InfoHeaderItem where info_header_id = ?";
        return getHibernateTemplate().find(hql, new Object[]{headerId});
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<InfoHeaderItem> getOnlineInfoHeaderItemByInfoId(long infoId) {
        String sql = "select infoHeader_item.info_header_id,  infoHeader_item.info_id, infoHeader_item.info_order,"
                + " infoHeader_item.description, infoHeader_item.original_info_order, infoHeader_item.update_time as updateTime"
                + " from info_header inner join infoHeader_item on info_header.id = infoHeader_item.info_header_id"
                + " where info_header.status = 1 and infoHeader_item.info_id = ?";

        Session session = null;
        List<InfoHeaderItem> results = new ArrayList<InfoHeaderItem>();
        try {
            session = getSession();
            Query query = session.createSQLQuery(sql).addScalar("info_header_id", Hibernate.LONG)
                    .addScalar("info_id", Hibernate.LONG).addScalar("info_order", Hibernate.INTEGER)
                    .addScalar("description", Hibernate.STRING).addScalar("original_info_order", Hibernate.INTEGER)
                    .addScalar("updateTime", Hibernate.TIMESTAMP)
                    .setResultTransformer(Transformers.aliasToBean(InfoHeaderItem.class));
            query.setLong(0, infoId);
            results = query.list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null)
                releaseSession(session);
        }
        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<InfoHeaderItem> getAllInfoHeaderItemByInfoId(long infoId) {
        String hql = "from InfoHeaderItem where info_id= ?";
        return getHibernateTemplate().find(hql, new Long[]{infoId});
    }

    @SuppressWarnings("unchecked")
    @Override
    public InfoHeaderItem get(long headerId, long infoId) {
        String hql = "from InfoHeaderItem where info_header_id = ? and info_id= ?";
        List<InfoHeaderItem> list = getHibernateTemplate().find(hql, new Long[]{headerId, infoId});
        return list == null || list.size() == 0 ? null : list.get(0);
    }
}